package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection {
	private Connection mMySQLConnection;

	public void connect() throws SQLException, ClassNotFoundException {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/book";
		String user = "root";
		String password = "";
		
		Class.forName(driver);
		mMySQLConnection = DriverManager.getConnection(url, user, password);
		if (mMySQLConnection.isClosed()) {
			throw new SQLException("Connection is closed.");
		}
	}

	public ResultSet query(String pQuerySQL) throws SQLException {
		Statement statement = mMySQLConnection.createStatement();
		return statement.executeQuery(pQuerySQL);
	}

	public int update(String pUpdateSql) throws SQLException {
		Statement statement = mMySQLConnection.createStatement();
		return statement.executeUpdate(pUpdateSql);
	}

	public void close() throws SQLException {
		mMySQLConnection.close();
	}

	public boolean isConnected() {
		try {
			return mMySQLConnection != null && !mMySQLConnection.isClosed();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
}
